package server;

import java.net.Socket;

import common.ConnectionManager;
import common.ControlMessage;
import common.Logger;
import common.Message;
import common.MessageType;

public class MasterServer extends Thread {
	
	private Server s = null;
	
	private String ip = null;
	private int port = 0;
	
	private boolean connected = false;
	
	private boolean status = true;
	
	private Logger log = null;
	
	private ConnectionManager connManager = null;
	
	public MasterServer(Server s, String ip, int port, Logger log) {
		this.ip = ip;
		this.port = port;
		this.log = log;
		this.s = s;
		
		try {
			connManager = new ConnectionManager(new Socket(ip, port));
		} catch (Exception e) {
			log.log("Error: cannot connect to Master Server (" + ip + ", " + port + ")");
			status = false;
			//e.printStackTrace();
		}
	}
	
	public Server getServer() {
		return s;
	}
	
	public void setServer(Server s) {
		this.s = s;
	}

	public String getIp() {
		return ip;
	}

	public int getPort() {
		return port;
	}
	
	public void close() {
		Message disconnect = new Message(MessageType.DISCONNECT, "Bye", false);
		connManager.sendMessage(disconnect);
	}
	
	public void run() {
		
		if (status == false) {
			s.ms = null;
			return;
		}
		
		int p = s.getServerSocket().getLocalPort();
		
		Message connect = new Message(MessageType.CONNECT, Integer.toString(p), false);
		
		connManager.sendMessage(connect);
		Message ans = connManager.receiveMessage(); 
		
		if ((ans != null) && (ans.getType() == MessageType.CONNECT)) {
			log.log("Logged to server");
			connected = true;;
		} else {
			log.log("Failed to connect to the Master Server");
			return;
		}
		
		while (connected) {
				
				ControlMessage msg = connManager.receiveMessage();
				
				if (msg != null) {
					if (msg.getType() == MessageType.DISCONNECT) {
						log.log("Master Server dies");
						s.ms = null;
						connManager.close();
						connected = false;
					}
					
				}
			}
		
	}
	
}
